package com.wjw.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static SessionFactory sessionFactory;
    static {
        //读取hibernate配置文件
        Configuration configuration=new Configuration().configure();
        //创建SessionFactory工厂对象
        sessionFactory=configuration.buildSessionFactory();
    }

    /**
     * 获取session
     * @return
     */
    public static Session getSession(){
        //openSession需要关闭资源  getCurrentSession()需在hibernate配置文件中配置线程上下文
        return sessionFactory.openSession();
    }

    /**
     * 关闭session
     * @param session
     */
    public static void closeSession(Session session){
        if(null!=session&&session.isOpen()){
            session.close();
        }
        sessionFactory.close();
    }
}
